package com.aurora.source.source.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aurora.source.R;
import com.aurora.source.base.BaseActivity;
import com.aurora.source.source.presenter.SplashPresenter;
import com.aurora.source.source.view.ISplashView;
import com.aurora.source.util.SPUtils;
import com.aurora.source.widget.PrivacyPolicyPopupWindow;
import com.bumptech.glide.Glide;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * @author: Lance
 * @description: 欢迎页
 * @date: 2018/7/10 10:12
 */
public class SplashActivity extends BaseActivity<SplashPresenter> implements ISplashView {
    private PrivacyPolicyPopupWindow mPrivacyPolicyPopupWindow = null;

    @BindView(R.id.iv_launch)
    ImageView mIvLaunch;
    @BindView(R.id.vp_splash)
    ViewPager mVpSplash;
    @BindView(R.id.ll_dot)
    LinearLayout mLlDot;

    private ArrayList<Integer> mList = new ArrayList<>();//图片list

    private boolean isFirst = true;// 是否第一次进入

    /**
     * 用于设置自动轮播
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            try {
                if (mVpSplash.getCurrentItem() == mList.size() - 1) { //最后一页
                    gotoActivity(LoginActivity.class, true);
                    return;
                }
                mVpSplash.setCurrentItem(mVpSplash.getCurrentItem() + 1);
                mHandler.sendEmptyMessageDelayed(0, 3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public int bindLayout() {
        return R.layout.activity_splash;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {
        try {

            // mList.add(R.drawable.splash);
            mList.add(R.drawable.splash);
            // initDots();// 初始化 图片下方的圆点
            mVpSplash.setAdapter(new SplashPagerAdapter());
            mVpSplash.setCurrentItem(0);
            //  updateIntroAndDot();// 更新数据与圆点
            initListener();// viewpager 监听器
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        try {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIvLaunch.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //处理完后remove掉，至于为什么，后面有解释
                mIvLaunch.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                boolean isAgree = (Boolean) SPUtils.get(SplashActivity.this,"agree_privacy",false);
                if(isAgree){
                    mHandler.sendEmptyMessageDelayed(0, 3000);
                }else {
                    privacyPolicyPopupWindow();
                }
            }
        });

    }

    @Override
    public void doBusiness() {
        //  basePresenter.doLogin("name","pass");
    }


    public void privacyPolicyPopupWindow(){
        try{
            if(mPrivacyPolicyPopupWindow==null){
                mPrivacyPolicyPopupWindow = new PrivacyPolicyPopupWindow(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()){
                            case R.id.tv_privacy_policy_sure:
                                SPUtils.put(SplashActivity.this,"agree_privacy",true);
                                mPrivacyPolicyPopupWindow.dismiss();
                                mHandler.sendEmptyMessageDelayed(0, 2000);
                                break;
                            case R.id.tv_privacy_policy_no:
                                mPrivacyPolicyPopupWindow.dismiss();
                                finish();
                                break;
                        }
                    }
                },mIvLaunch);
            }
            mPrivacyPolicyPopupWindow.showAtLocation(mIvLaunch,Gravity.CENTER|Gravity.CENTER_HORIZONTAL,0,0);
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    //初始化图片下方的圆点
    private void initDots() {
        try {
            for (int i = 0; i < mList.size(); i++) {
                View view = new View(this);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50, 10);
                if (i != 0) {
                    params.leftMargin = 5;
                }
                view.setLayoutParams(params);
                view.setBackgroundResource(R.drawable.sel_splash_dot);
                mLlDot.addView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //更新数据与圆点
    private void updateIntroAndDot() {
        try {
            int currentPage = mVpSplash.getCurrentItem();
            for (int i = 0; i < mLlDot.getChildCount(); i++)
                mLlDot.getChildAt(i).setEnabled(i == currentPage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 初始化监听器，当页面改变时，更新其相应数据
    private void initListener() {
        mVpSplash.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                try {
                    //   updateIntroAndDot();
                    int currentPage = mVpSplash.getCurrentItem();
                    //到了第二页,两秒后跳转到登录
                    if ((currentPage == mList.size() - 1) && isFirst) {
                        isFirst = false;
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startLoginActivity();
                            }
                        }, 2000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    //界面跳转
    private void startLoginActivity() {
        gotoActivity(LoginActivity.class, true);
    }

    //ViewPager的主体部分
    class SplashPagerAdapter extends PagerAdapter {

        /**
         * 返回多少page
         */
        public int getCount() {
            return mList.size();
        }

        /**
         * view滑动到一半时是否创建新的view
         * true:表示不去创建，使用缓存；false:去重新创建
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 类似于BaseAdapter的getView方法
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = null;
            try {
                view = View.inflate(activity, R.layout.item_splash, null);
                ImageView imageView = (ImageView) view.findViewById(R.id.iv_splash);
                Integer ad = mList.get(position % mList.size());
                Glide.with(activity)
                        .load(ad)
                        .into(imageView);
                container.addView(view);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return view;
        }

        /**
         * @param position:当前需要销毁第几个page
         * @param object:当前需要销毁的page
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

    }

    @Override
    public SplashPresenter attach() {
        return new SplashPresenter(this);
    }

    @Override
    protected void onDestroy() {
        try {
            super.onDestroy();
            isFirst = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
